<template>
  <div style="display: inline-flex">
    <div @click="handleUpload">
      <slot></slot>
    </div>
  </div>
  <a-form-item-rest>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      width="500px"
      heigt="300px"
      :closable="false"
      :mask-closable="false"
      :keyboard="false"
      :footer="null"
      destroyOnClose
    >
      <a-upload-dragger
        name="file"
        :customRequest="importExcel"
        :headers="headers"
        accept=".xlsx,.xls"
        :showUploadList="false"
        :beforeUpload="beforeUpload"
      >
        <p class="ant-upload-drag-icon">
          <CloudUploadOutlined />
        </p>
        <p class="ant-upload-text">点击区域，或将文件拖拽到此处</p>
        <p class="ant-upload-hint">Click or drag file to this area to upload</p>
      </a-upload-dragger>
      <div style="text-align: center; padding-top: 20px">
        <!-- 自定义按钮区域插槽 -->
        <slot name="customBTN"></slot>
        <a-button @click="handleCancel" style="margin-left: 10px; background-color: grey"
          ><span style="color: white">关闭</span></a-button
        >
      </div>
    </BasicModal>
    <BasicModal
      v-bind="$attrs"
      @register="registerModalTable"
      width="1000px"
      heigt="800px"
      :closable="false"
      :mask-closable="false"
      :keyboard="false"
      @ok="handelErrorCancel"
      @cancel="handelErrorCancel"
      destroyOnClose
    >
    </BasicModal>
  </a-form-item-rest>
</template>
<script lang="ts">
import {defineComponent, reactive, ref} from 'vue';
import {CloudUploadOutlined} from '@ant-design/icons-vue';
import {BasicModal, useModal} from '/@/components/Modal';
import {useMessage} from '/@/hooks/web/useMessage';
import {getToken} from '/@/utils/auth';
import {uploadAction} from '../../../api/sys/file';
import {timestamp} from '@vueuse/shared';

export default defineComponent({
    name: 'JinhuiImportExcel',
    components: {
      BasicModal,
      CloudUploadOutlined,
    },
    props: {
      //导入的sheetMap
      importMap: {
        type: Object,
        default: null,
        required: true,
      },
      //业务类型
      businessType: {
        type: String,
        default: '',
      },
      //是否上传附件
      isUpload: {
        type: Boolean,
        default: false,
      },
      //导出文件名称
      tempFileName: {
        type: String,
        required: true,
      },
      // 导入失败的文件名
      importFailedName: {
        type: String,
        default: null,
      },
      //URL地址
      importUrl: {
        type: String,
        required: true,
      },
      //是否显示下载模板按钮
      showTemplateDownloadBTN:{
        type: Boolean,
        default: true
      }
    },
    emits: ['success', 'error', 'file'],
    setup(props, { emit }) {
      const [registerModal, { openModal }] = useModal();
      const [registerModalTable, { openModal: openModalTable }] = useModal();
      const inputRef = ref<HTMLInputElement | null>(null);
      const importExcelUrl = props.importUrl;
      const { createMessage } = useMessage();
      //token
      const headers = ref<object>({
        'jinhui-token': getToken(),
        Timestamp: Date.now(),
      });
      /**
       * 导入数据
       */
      let fileName = ref();
      let errorColumns: Array<any> = [];
      let filePath = ref();
      let allList = ref(Array<any>);
      let dataList: Array<any> = [];
      function importExcel(info) {
        let formData = new FormData();
        formData.append('file', info.file);
        createMessage.loading({content: '正在导入中', duration: 0 });
        uploadAction(importExcelUrl, formData).then((res) => {
          //正在导入中的loading的关闭
          createMessage.destroy();
          if (res != null) {
            var resObj = eval('(' + res + ')');
            if (resObj.success) {
              createMessage.success('导入成功');
              emit('success');
              handleCancel();
            } else {
              // allList.value = res.data;
              // for (let i = 0; i < allList.value.length; i++) {
              //   dataList = res.data[i];
              //   errorColumns = [];
              //   errorColumns.push({
              //     title: '行号',
              //     align: 'center',
              //     dataIndex: 'rowNum',
              //   });
              //   errorColumns.push({
              //     title: '错误信息',
              //     align: 'center',
              //     dataIndex: 'msg',
              //   });
              //   Object.entries(res.row[i]).forEach((label) => {
              //     let [_key, _value] = label;
              //     if (_key != 'msg') {
              //       errorColumns.push({
              //         title: _value,
              //         align: 'center',
              //         dataIndex: _key,
              //       });
              //     }
              //   });
              //   dataList['colums'] = errorColumns;
              //   dataList['sheetName'] = res.sheetName[i];
              // }
              // fileName.value = props.importFailedName
              //   ? props.importFailedName + '_' + timestamp() + '.xlsx'
              //   : res.fileName;
              // filePath.value = res.fullPath;
              // openModalTable(true);
              createMessage.error('导入失败 : '+resObj.data);
            }
          } else {
            createMessage.error('导入失败');
          }
        });
      }
      /**
       * @description: 点击上传按钮
       */
      function handleUpload() {
        openModal(true, {});
      }
      function handleCancel() {
        openModal(false, {});
      }
      function handelErrorCancel() {
        openModal(false, {});
        openModalTable(false, {});
      }

      /**
       * 上传前校验
       */
      function beforeUpload(file) {
        return new Promise((resolve, reject) => {
          let fileType = file.type;
          // if (fileType.indexOf('spreadsheetml.sheet') < 0) {
          //   createMessage.warning('请选择excel文件');
          //   return reject;
          // }
          return resolve(true);
        });
      }

      function callback(key) {
        //console.log(key)
      }

      //下载
      // function down() {
      //   // 错误 下载
      //   fileName.value = fileName.value;
      //   downFile(downLoadFile).then((data) => {
      //     if (!data) {
      //       createMessage.warning('文件下载失败');
      //       return;
      //     }
      //     if (typeof window.navigator.msSaveBlob !== 'undefined') {
      //       window.navigator.msSaveBlob(
      //         new Blob([data], { type: 'application/vnd.ms-excel' }),
      //         fileName.value,
      //       );
      //     } else {
      //       let url = window.URL.createObjectURL(
      //         new Blob([data], { type: 'application/vnd.ms-excel' }),
      //       );
      //       let link = document.createElement('a');
      //       link.style.display = 'none';
      //       link.href = url;
      //       link.setAttribute('download', fileName.value);
      //       document.body.appendChild(link);
      //       link.click();
      //       document.body.removeChild(link); //下载完成移除元素
      //       window.URL.revokeObjectURL(url); //释放掉blob对象
      //     }
      //   });
      // }

      const formState = reactive<Record<string, any>>({});
      return {
        handleUpload,
        inputRef,
        formState,
        registerModal,
        registerModalTable,
        handleCancel,
        importExcelUrl,
        beforeUpload,
        headers,
        importExcel,
        fileName,
        errorColumns,
        filePath,
        allList,
        dataList,
        callback,
        //down,
        handelErrorCancel,
      };
    },
  });
</script>
<style lang="less" scoped>
  .ant-upload.ant-upload-drag .ant-upload {
    padding: 27px;
  }
</style>
